from django.db.models import Q, ProtectedError
from rest_framework.views import APIView
from app01.models import Cabinet, MachineRoom, IDCDevice
from django.http import JsonResponse
from app01.Baseview import BasedAPIView


class CabinetView(BasedAPIView):
    def get(self, request, *args, **kwargs):
        module = kwargs.get('module')
        if module == 'get_cabinet_all':
            return self.get_cabinet_all(request)
        if module == 'getById':
            return self.getById(request)

    def post(self, request, *args, **kwargs):
        module = kwargs.get('module')
        if module == 'add':
            return self.add(request)
        if module == 'edit':
            return self.edit(request)
        if module == 'dele':
            return self.dele(request)

    def get_cabinet_all(self, request, format=None):
        uid = request.GET.get('userId', None)
        status = request.GET.get('status', None)
        cabinet_name = request.GET.get('cabinet_name', None)
        machine_room_id = request.GET.get('room', None)
        query = Q()
        if uid is not None:
            query &= Q(id=uid)
        if machine_room_id is not None:
            query &= Q(machine_room__id=machine_room_id)
        if cabinet_name is not None:
            query &= Q(cabinet_number__icontains=cabinet_name)
        if status is not None:
            query &= Q(status=status)

        cabinet_data = Cabinet.objects.filter(query).order_by('-id')
        total = cabinet_data.count()
        cabinet_dic = []
        for item in cabinet_data:
            status_desc = dict(Cabinet.STATUS_CHOICES).get(item.status, '')
            res_data = {
                'id': item.id,
                'number': item.cabinet_number,
                'status': {
                    'id': item.status,
                    'value': status_desc
                },
                'machine_room': {
                    'id': item.machine_room.id,
                    'name': item.machine_room.room_name,
                },
                "time": item.UpdatedTime.strftime("%Y-%m-%d %H:%M:%S"),

            }
            cabinet_dic.append(res_data)
        machine_rooms = MachineRoom.objects.all()
        ch_status = Cabinet.STATUS_CHOICES
        options = {
            'status': [
                {
                    'id': idx,
                    'value': choice[0],
                    'label': choice[1]
                }
                for idx, choice in enumerate(ch_status)
            ],
            'machine_rooms': [
                {
                    'id': room.id,
                    'name': room.room_name
                }
                for room in machine_rooms
            ],
        }
        data = {
            'total': total,
            'data': cabinet_dic,
            'options': options
        }
        return super().success(data=data)

    def getById(self, request, format=None):
        uid = request.GET.get('id')
        cabinet = Cabinet.objects.get(id=uid)
        data = {
            'id': cabinet.id,
            'cabinet_number': cabinet.cabinet_number,
            'room': cabinet.machine_room.id,
            'status': cabinet.status,
            'time': cabinet.UpdatedTime.strftime("%Y-%m-%d %H:%M:%S"),
        }
        return super().success(data=data)

    def add(self, request):
        cabinet_number = request.data.get('cabinet_number')
        room_id = request.data.get('room')

        if not room_id:
            return super().error(msg="机房 ID 不能为空")
        try:
            # 获取对应的机房实例根据name或者id
            # machine_room = MachineRoom.objects.get(room_name=room_name)
            machine_room_id = MachineRoom.objects.get(id=room_id)
            # 创建新的机柜实例
            # cabinet = Cabinet(cabinet_number=cabinet_name, machine_room=machine_room)
            cabinet = Cabinet(cabinet_number=cabinet_number, machine_room=machine_room_id)
            cabinet.save()

            # 构造返回的数据
            data = {
                'id': cabinet.id,
                'room': cabinet.cabinet_number,
                # 'room_name': cabinet.machine_room.room_name  # 使用 room_name
                'room_name': cabinet.machine_room.room_name  # 使用 room_name
            }
            return super().success(msg="新增成功", data=data)
        except Exception as e:
            return super().error(msg=str(e))

    def edit(self, request):
        uid = request.data.get('id', None)
        cabinet_number = request.data.get('cabinet_number', None)
        status = request.data.get('status', None)
        room_id = request.data.get('room', None)
        try:
            cabinet = Cabinet.objects.get(id=uid)
            cabinet.cabinet_number = cabinet_number
            cabinet.machine_room = MachineRoom.objects.get(id=room_id)
            cabinet.status = status
            cabinet.save()
            data = {
                'id': cabinet.id,
                'name': cabinet.cabinet_number,
                'room': cabinet.machine_room.id,
                "status": cabinet.status,
                "time": cabinet.UpdatedTime.strftime("%Y-%m-%d %H:%M:%S"),
            }
            return super().success(msg="更新成功", data=data)
        except Exception as e:
            return super().error(msg=str(e))

    def dele(self, request):
        '''删除数据'''
        ids = request.GET.get("id", "")
        if ids == "":
            return super().error(msg="ID不能为空")
        ids = ids.split(",")  # 将字符串切割为列表
        ids_int = []
        for i in ids:
            if i == "":
                continue
            ids_int.append(int(i))  # 将id转换为数字类型 然后添加到新的列表中
        Obj = Cabinet.objects.filter(id__in=ids_int)  # id__in为 根据id字段 传入一个列表 批量查询需要删除的数据
        if not Obj.exists():  # 检测数据是否存在
            return super().error(msg="数据不存在")
        for cabinet in Obj:
            if cabinet.devices.exists():
                return super().error(msg=f'{cabinet.cabinet_number} 有关联的设备，请先删除设备后再尝试删除机柜。')
        Obj.delete()  # 删除查询到的数据
        return super().success(msg="删除成功")
